import { PORT1 } from "@/api/config/servicePort";
import http from "@/api";
import { ReqPage, ResPage } from "@/api/interface";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { useUserStore } from "@/stores/modules/user";

// AI Chat 消息
export namespace ChatMessage {
  export interface ResChatMessage {
    id: number; // 主键
    chatId: number; // 对话编号
    replyId: number; // 回复消息编号
    type: string; // 消息类型
    userId: number; // 用户编号
    roleId: number; // 角色编号
    segmentIds: string; // 段落编号数组
    model: string; // 模型标志
    modelId: number; // 模型编号
    content: string; // 聊天内容
    useContext: number; // 是否携带上下文
    createBy: number;
    createTime: Date;
    updateBy: number;
    updateTime: Date;
    isDeleted: Boolean;
  }

  export interface ReqChatMessage extends ReqPage {
    id: number; // 主键
    chatId: number; // 对话编号
    replyId: number; // 回复消息编号
    type: string; // 消息类型
    userId: number; // 用户编号
    roleId: number; // 角色编号
    segmentIds: string; // 段落编号数组
    model: string; // 模型标志
    modelId: number; // 模型编号
    content: string; // 聊天内容
    useContext: number; // 是否携带上下文
    createBy: number;
    createTime: Date;
    updateBy: number;
    updateTime: Date;
    isDeleted: Boolean;
  }
}
const userStore = useUserStore();
// 发送 Stream 消息
// 为什么不用 axios 呢？因为它不支持 SSE 调用
export const sendChatMessageStream =  async (
  conversationId: number,
  content: string,
  ctrl,
  enableContext: boolean,
  onMessage,
  onError,
  onClose
) => {
  return fetchEventSource(`${import.meta.env.VITE_API_URL + PORT1 }/ai/chat-message/send-stream`, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      "x-access-token": userStore.token
    },
    openWhenHidden: true,
    body: JSON.stringify({
      conversationId,
      content,
      useContext: enableContext
    }),
    onmessage: onMessage,
    onerror: onError,
    onclose: onClose,
    signal: ctrl.signal
  })
};

// 查询会话的消息列表
export const getListByChatId = (chatId: number) => {
  return http.get<ChatMessage.ResChatMessage[]>(PORT1 + `/ai/chat-message/list-by-chat-id/${chatId}`);
};

// 查询AI Chat 消息分页
export const getChatMessagePage = (params: ChatMessage.ReqChatMessage) => {
  return http.get<ResPage<ChatMessage.ResChatMessage>>(PORT1 + `/ai/chat-message/page`, params);
};
// 查询AI Chat 消息详情
export const getChatMessage = (id: number) => {
  return http.get<ChatMessage.ResChatMessage>(PORT1 + `/ai/chat-message/get/${id}`);
};

// 新增AI Chat 消息
export const createChatMessage = (data: ChatMessage.ReqChatMessage) => {
  return http.post<Boolean>(PORT1 + `/ai/chat-message/create`, data);
};

// 修改AI Chat 消息
export const updateChatMessage = (data: ChatMessage.ReqChatMessage) => {
  return http.put<Boolean>(PORT1 + `/ai/chat-message/update`, data);
};
// 删除AI Chat 消息
export const deleteChatMessage = (id: number) => {
  return http.delete<Boolean>(PORT1 + `/ai/chat-message/delete/${id}`);
};
